package classes
{
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class QbeHandler extends EventDispatcher
	{
		private var _lastResult:ArrayCollection;
		private var _tagList:ArrayCollection;
		private static var instance:QbeHandler;
		
		[Bindable ("qbeResult")]
		public function get lastResult():ArrayCollection{
			return _lastResult;
		}
		
		[Bindable ("qbeResult")]
		public function get tagList():ArrayCollection{
			return _tagList;
		}
		
		public function QbeHandler(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public function performQbe(fileReference:FileReference):void{
			fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadCompletedHandler);
			fileReference.upload(new URLRequest(Settings.getInstance().qbeServletURL));
			dispatchEvent(new Event("uploadStarted"));
		}
		
		private function uploadCompletedHandler(event:DataEvent):void{
			dispatchEvent(new Event("retrievingRss"));
			event.target.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadCompletedHandler);
			var servletReq:HTTPService = new HTTPService();
			servletReq.method = "POST";
			servletReq.url = Settings.getInstance().requestRSSServletURL;
			servletReq.addEventListener(ResultEvent.RESULT, requestRSSResultHandler);
			servletReq.send({"sessionID": event.data.toString()});
		}
		
		private function requestRSSResultHandler(event:ResultEvent):void{
			_lastResult = Parser.parseServletResult(event);
			if(_lastResult == null){
				dispatchEvent(new Event("qbeError"));
			}else{
				_tagList = getUniqueTagList(_lastResult);
				dispatchEvent(new ResultEvent("qbeResult",false,true,lastResult));
			}
		}
		
		private function getUniqueTagList(imgs:ArrayCollection):ArrayCollection{
			var tags:ArrayCollection = new ArrayCollection;
			for each(var img:ReturnedImage in imgs){
				for each(var tag:String in img.tags){
					if(!tags.contains(tag))
						tags.addItem(tag);
				}
			}
			return tags;
		}
				
		public static function getInstance():QbeHandler{
			if(instance==null)
				instance = new QbeHandler();
			return instance;
		}
	}
}